{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Web Devs Quickstart\n",
    "\n",
    "> A fast introduction to FastHTML for experienced web developers.\n",
    "\n",
    "- order: 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "from fasthtml.common import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::: {.callout-note}\n",
    "We're going to be adding more to this document, so check back frequently for updates.\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "from nbdev.showdoc import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Installation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```bash\n",
    "pip install python-fasthtml\n",
    "````"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A Minimal Application\n",
    "\n",
    "A minimal FastHTML application looks something like this:\n",
    "\n",
    "``` {.python filename=\"main.py\" code-line-numbers=\"true\"}\n",
    "from fasthtml.common import *  # <1>\n",
    "\n",
    "app, rt = fast_app()  # <2>\n",
    "\n",
    "@rt(\"/\")  # <3>\n",
    "def get():  # <4>\n",
    "    return Titled(\"FastHTML\", P(\"Let's do this!\"))  # <5>\n",
    "\n",
    "serve()  # <6>\n",
    "```\n",
    "\n",
    "1. We import what we need for rapid development! A carefully-curated set of FastHTML functions and other Python objects is brought into our global namespace for convenience.\n",
    "2. We instantiate a FastHTML app with the `fast_app()` utility function. This provides a number of really useful defaults that we'll take advantage of later in the tutorial. \n",
    "3. We use the `rt()` decorator to tell FastHTML what to return when a user visits `/` in their browser.\n",
    "4. We connect this route to HTTP GET requests by defining a view function called `get()`.\n",
    "5. A tree of Python function calls that return all the HTML required to write a properly formed web page. You'll soon see the power of this approach.\n",
    "6. The `serve()` utility configures and runs FastHTML using a library called `uvicorn`.\n",
    "\n",
    "Run the code:\n",
    "\n",
    "```bash\n",
    "python main.py\n",
    "```\n",
    "\n",
    "The terminal will look like this:\n",
    "\n",
    "```bash\n",
    "INFO:     Uvicorn running on http://0.0.0.0:5001 (Press CTRL+C to quit)\n",
    "INFO:     Started reloader process [58058] using WatchFiles\n",
    "INFO:     Started server process [58060]\n",
    "INFO:     Waiting for application startup.\n",
    "INFO:     Application startup complete.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Confirm FastHTML is running by opening your web browser to [127.0.0.1:5001](http://127.0.0.1:5001). You should see something like the image below:\n",
    "\n",
    "![](quickstart-web-dev/quickstart-fasthtml.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::: {.callout-note}\n",
    "While some linters and developers will complain about the wildcard import, it is by design here and perfectly safe. FastHTML is very deliberate about the objects it exports in `fasthtml.common`. If it bothers you, you can import the objects you need individually, though it will make the code more verbose and less readable.\n",
    "\n",
    "If you want to learn more about how FastHTML handles imports, we cover that [here](https://docs.fastht.ml/explains/faq.html#why-use-import).\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A Minimal Charting Application\n",
    "\n",
    "The `Script` function allows you to include JavaScript. You can use Python to generate parts of your JS or JSON like this:\n",
    "\n",
    "```python\n",
    "import json\n",
    "from fasthtml.common import * \n",
    "\n",
    "app, rt = fast_app(hdrs=(Script(src=\"https://cdn.plot.ly/plotly-2.32.0.min.js\"),))\n",
    "\n",
    "data = json.dumps({\n",
    "    \"data\": [{\"x\": [1, 2, 3, 4],\"type\": \"scatter\"},\n",
    "            {\"x\": [1, 2, 3, 4],\"y\": [16, 5, 11, 9],\"type\": \"scatter\"}],\n",
    "    \"title\": \"Plotly chart in FastHTML \",\n",
    "    \"description\": \"This is a demo dashboard\",\n",
    "    \"type\": \"scatter\"\n",
    "})\n",
    "\n",
    "\n",
    "@rt(\"/\")\n",
    "def get():\n",
    "  return Titled(\"Chart Demo\", Div(id=\"myDiv\"),\n",
    "    Script(f\"var data = {data}; Plotly.newPlot('myDiv', data);\"))\n",
    "\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Debug Mode\n",
    "\n",
    "When we can't figure out a bug in FastHTML, we can run it in `DEBUG` mode. When an error is thrown, the error screen is displayed in the browser. This error setting should never be used in a deployed app.\n",
    "\n",
    "```python\n",
    "from fasthtml.common import *\n",
    "\n",
    "app, rt = fast_app(debug=True)  # <1>\n",
    "\n",
    "@rt(\"/\")\n",
    "def get():\n",
    "    1/0  # <2>\n",
    "    return Titled(\"FastHTML Error!\", P(\"Let's error!\"))\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "1. `debug=True` sets debug mode on. \n",
    "2. Python throws an error when it tries to divide an integer by zero."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Routing\n",
    "\n",
    "FastHTML builds upon FastAPI's friendly decorator pattern for specifying URLs, with extra features:\n",
    "\n",
    "```{.python filename=\"main.py\" code-line-numbers=\"true\"}\n",
    "from fasthtml.common import * \n",
    "\n",
    "app, rt = fast_app()\n",
    "\n",
    "@rt(\"/\")  # <1>\n",
    "def get():\n",
    "  return Titled(\"FastHTML\", P(\"Let's do this!\"))\n",
    "\n",
    "@rt(\"/hello\")  # <2>\n",
    "def get():\n",
    "  return Titled(\"Hello, world!\")\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "1. The \"/\" URL on line 5 is the home of a project. This would be accessed at [127.0.0.1:5001](http://127.0.0.1:5001).\n",
    "2. \"/hello\" URL on line 9 will be found by the project if the user visits [127.0.0.1:5001/hello](http://127.0.0.1:5001/hello).\n",
    "\n",
    "::: {.callout-tip}\n",
    "It looks like `get()` is being defined twice, but that's not the case. Each function decorated with `rt` is totally separate, and is injected into the router. We're not calling them in the module's  namespace (`locals()`). Rather, we're loading them into the routing mechanism using the `rt` decorator.\n",
    ":::\n",
    "\n",
    "You can do more! Read on to learn what we can do to make parts of the URL dynamic."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Variables in URLs\n",
    "\n",
    "You can add variable sections to a URL by marking them with `{variable_name}`. Your function then receives the `{variable_name}` as a keyword argument, but only if it is the correct type. Here's an example:\n",
    "\n",
    "```{.python filename=\"main.py\" code-line-numbers=\"true\"}\n",
    "from fasthtml.common import * \n",
    "\n",
    "app, rt = fast_app()\n",
    "\n",
    "@rt(\"/{name}/{age}\")  # <1>\n",
    "def get(name: str, age: int):  # <2>\n",
    "  return Titled(f\"Hello {name.title()}, age {age}\")  # <3>\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "1. We specify two variable names, `name` and `age`.\n",
    "2. We define two function arguments named identically to the variables. You will note that we specify the Python types to be passed.\n",
    "3. We use these functions in our project.\n",
    "\n",
    "\n",
    "Try it out by going to this address: [127.0.0.1:5001/uma/5](http://127.0.0.1:5001/uma/5). You should get a page that says,\n",
    "\n",
    "> \"Hello Uma, age 5\".\n",
    "\n",
    "\n",
    "### What happens if we enter incorrect data?\n",
    "\n",
    "The [127.0.0.1:5001/uma/5](http://127.0.0.1:5001/uma/5) URL works because `5` is an integer. If we enter something that is not, such as [127.0.0.1:5001/uma/five](http://127.0.0.1:5001/uma/five), then FastHTML will return an error instead of a web page.\n",
    "\n",
    "::: {.callout-note}\n",
    "### FastHTML URL routing supports more complex types\n",
    "\n",
    "The two examples we provide here use Python's built-in `str` and `int` types, but you can use your own types, including more complex ones such as those defined by libraries like [attrs](https://pypi.org/project/attrs/), [pydantic](https://pypi.org/project/pydantic/), and even [sqlmodel](https://pypi.org/project/sqlmodel/). \n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## HTTP Methods\n",
    "\n",
    "FastHTML matches function names to HTTP methods. So far the URL routes we've defined have been for HTTP GET methods, the most common method for web pages.\n",
    "\n",
    "Form submissions often are sent as HTTP POST. When dealing with more dynamic web page designs, also known as Single Page Apps (SPA for short), the need can arise for other methods such as HTTP PUT and HTTP DELETE. The way FastHTML handles this is by changing the function name.\n",
    "\n",
    "```{.python filename=\"main.py\" code-line-numbers=\"true\"}\n",
    "from fasthtml.common import * \n",
    "\n",
    "app, rt = fast_app()\n",
    "\n",
    "@rt(\"/\")  \n",
    "def get(): # <1>\n",
    "  return Titled(\"HTTP GET\", P(\"Handle GET\"))\n",
    "\n",
    "@rt(\"/\")  \n",
    "def post(): # <2>\n",
    "  return Titled(\"HTTP POST\", P(\"Handle POST\"))\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "1. On line 6 because the `get()` function name is used, this will handle HTTP GETs going to the `/` URI.\n",
    "2. On line 10 because the `post()` function name is used, this will handle HTTP POSTs going to the `/` URI."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## CSS Files and Inline Styles\n",
    "\n",
    "Here we modify default headers to demonstrate how to use the [Sakura CSS microframework](https://github.com/oxalorg/sakura) instead of FastHTML's default of Pico CSS.\n",
    "\n",
    "```{.python filename=\"main.py\" code-line-numbers=\"true\"}\n",
    "from fasthtml.common import * \n",
    "\n",
    "app, rt = fast_app(\n",
    "    pico=False,  # <1>\n",
    "    hdrs=(\n",
    "        Link(rel='stylesheet', href='assets/normalize.min.css', type='text/css'),\n",
    "        Link(rel='stylesheet', href='assets/sakura.css', type='text/css'),  # <2>\n",
    "        Style(\"p {color: red;}\")  # <3>\n",
    "))\n",
    "\n",
    "@app.get(\"/\")\n",
    "def home():\n",
    "    return Titled(\"FastHTML\",\n",
    "        P(\"Let's do this!\"),\n",
    "    )\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "1. By setting `pico` to `False`, FastHTML will not include `pico.min.css`.\n",
    "2. This will generate an HTML `<link>` tag for sourcing the css for Sakura.\n",
    "3. If you want an inline styles, the `Style()` function will put the result into the HTML."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Other Static Media File Locations\n",
    "\n",
    "As you saw, `Script` and `Link` are specific to the most common static media use cases in web apps: including JavaScript, CSS, and images. But it also works with videos and other static media files. The default behavior is to look for these files in the root directory - typically we don't do anything special to include them.\n",
    "\n",
    "FastHTML also allows us to define a route that uses `FileResponse` to serve the file at a specified path. This is useful for serving images, videos, and other media files from a different directory without having to change the paths of many files. So if we move the directory containing the media files, we only need to change the path in one place. In the example below, we call images from a directory called `public`.\n",
    "\n",
    "```python\n",
    "@rt(\"/{fname:path}.{ext:static}\")\n",
    "async def get(fname:str, ext:str): \n",
    "    return FileResponse(f'public/{fname}.{ext}')\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Rendering Markdown\n",
    "\n",
    "```python\n",
    "from fasthtml.common import *\n",
    "\n",
    "hdrs = (MarkdownJS(), HighlightJS(langs=['python', 'javascript', 'html', 'css']), )\n",
    "\n",
    "app, rt = fast_app(hdrs=hdrs)\n",
    "\n",
    "content = \"\"\"\n",
    "Here are some _markdown_ elements.\n",
    "\n",
    "- This is a list item\n",
    "- This is another list item\n",
    "- And this is a third list item\n",
    "\n",
    "**Fenced code blocks work here.**\n",
    "\"\"\"\n",
    "\n",
    "@rt('/')\n",
    "def get(req):\n",
    "    return Titled(\"Markdown rendering example\", Div(content,cls=\"marked\"))\n",
    "\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code highlighting\n",
    "\n",
    "Here's how to highlight code without any markdown configuration.\n",
    "\n",
    "```python\n",
    "from fasthtml.common import *\n",
    "\n",
    "# Add the HighlightJS built-in header\n",
    "hdrs = (HighlightJS(langs=['python', 'javascript', 'html', 'css']),)\n",
    "\n",
    "app, rt = fast_app(hdrs=hdrs)\n",
    "\n",
    "code_example = \"\"\"\n",
    "import datetime\n",
    "import time\n",
    "\n",
    "for i in range(10):\n",
    "    print(f\"{datetime.datetime.now()}\")\n",
    "    time.sleep(1)\n",
    "\"\"\"\n",
    "\n",
    "@rt('/')\n",
    "def get(req):\n",
    "    return Titled(\"Markdown rendering example\",\n",
    "        Div(\n",
    "            # The code example needs to be surrounded by\n",
    "            # Pre & Code elements\n",
    "            Pre(Code(code_example))\n",
    "    ))\n",
    "\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Defining new `ft` components\n",
    "\n",
    "We can build our own `ft` components and combine them with other components. The simplest method is defining them as a function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<main>\n",
       "  <div class=\"hero\">\n",
       "    <h1>Hello World</h1>\n",
       "    <p>This is a hero statement</p>\n",
       "  </div>\n",
       "</main>\n",
       "\n",
       "```"
      ],
      "text/plain": [
       "['main',\n",
       " (['div',\n",
       "   (['h1', ('Hello World',), {}], ['p', ('This is a hero statement',), {}]),\n",
       "   {'class': 'hero'}],),\n",
       " {}]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def hero(title, statement):\n",
    "    return Div(H1(title),P(statement), cls=\"hero\")\n",
    "\n",
    "# usage example\n",
    "Main(\n",
    "    hero(\"Hello World\", \"This is a hero statement\")\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Pass through components\n",
    "\n",
    "For when we need to define a new component that allows zero-to-many components to be nested within them, we lean on Python's `*args` and `**kwargs` mechanism. Useful for creating page layout controls."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<main class=\"dashboard\">\n",
       "  <h1>Dashboard</h1>\n",
       "  <div>\n",
       "    <ul>\n",
       "      <li>0</li>\n",
       "      <li>1</li>\n",
       "      <li>2</li>\n",
       "    </ul>\n",
       "    <p class=\"description\">Some content</p>\n",
       "  </div>\n",
       "</main>\n",
       "\n",
       "```"
      ],
      "text/plain": [
       "['main',\n",
       " (['h1', ('Dashboard',), {}],\n",
       "  ['div',\n",
       "   (['ul', (['li', (0,), {}], ['li', (1,), {}], ['li', (2,), {}]), {}],\n",
       "    ['p', ('Some content',), {'class': 'description'}]),\n",
       "   {}]),\n",
       " {'class': 'dashboard'}]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def layout(*args, **kwargs):\n",
    "    \"\"\"Dashboard layout for all our dashboard views\"\"\"\n",
    "    return Main(\n",
    "        H1(\"Dashboard\"),\n",
    "        Div(*args, **kwargs),\n",
    "        cls=\"dashboard\",\n",
    "    )\n",
    "\n",
    "# usage example\n",
    "layout(\n",
    "    Ul(*[Li(o) for o in range(3)]),\n",
    "    P(\"Some content\", cls=\"description\"),\n",
    ")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dataclasses as ft components\n",
    "\n",
    "While functions are easy to read, for more complex components some might find it easier to use a dataclass."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<main>\n",
       "  <div class=\"hero\">\n",
       "    <h1>Hello World</h1>\n",
       "    <p>This is a hero statement</p>\n",
       "  </div>\n",
       "</main>\n",
       "\n",
       "```"
      ],
      "text/plain": [
       "['main',\n",
       " (Hero(title='Hello World', statement='This is a hero statement'),),\n",
       " {}]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass\n",
    "class Hero:\n",
    "    title: str\n",
    "    statement: str\n",
    "    \n",
    "    def __ft__(self):\n",
    "        \"\"\" The __ft__ method renders the dataclass at runtime.\"\"\"\n",
    "        return Div(H1(self.title),P(self.statement), cls=\"hero\")\n",
    "    \n",
    "# usage example\n",
    "Main(\n",
    "    Hero(\"Hello World\", \"This is a hero statement\")\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Testing views in notebooks\n",
    "\n",
    "Because of the ASGI event loop it is currently impossible to run FastHTML inside a notebook. However, we can still test the output of our views. To do this, we leverage Starlette, an ASGI toolkit that FastHTML uses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<!doctype html>\n",
      "\n",
      "<html>\n",
      "  <head>\n",
      "    <title>FastHTML is awesome</title>\n",
      "  </head>\n",
      "  <body>\n",
      "<main class=\"container\">\n",
      "  <h1>FastHTML is awesome</h1>\n",
      "  <p>The fastest way to create web apps in Python</p>\n",
      "</main>\n",
      "  </body>\n",
      "</html>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# First we instantiate our app, in this case we remove the\n",
    "# default headers to reduce the size of the output.\n",
    "app, rt = fast_app(default_hdrs=False)\n",
    "\n",
    "# Setting up the Starlette test client\n",
    "from starlette.testclient import TestClient\n",
    "client = TestClient(app)\n",
    "\n",
    "# Usage example\n",
    "@rt(\"/\")\n",
    "def get():\n",
    "    return Titled(\"FastHTML is awesome\", \n",
    "        P(\"The fastest way to create web apps in Python\"))\n",
    "\n",
    "print(client.get(\"/\").text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Strings and conversion order\n",
    "\n",
    "The general rules for rendering are: \n",
    "- `__ft__` method will be called (for default components like `P`, `H2`, etc. or if you define your own components)\n",
    "- If you pass a string, it will be escaped\n",
    "- On other python objects, `str()` will be called\n",
    "\n",
    "As a consequence, if you want to include plain HTML tags directly into e.g. a `Div()` they will get escaped by default (as a security measure to avoid code injections). This can be avoided by using `NotStr()`, a convenient way to reuse python code that returns already HTML. If you use pandas, you can use `pandas.DataFrame.to_html()` to get a nice table. To include the output a FastHTML, wrap it in `NotStr()`, like `Div(NotStr(df.to_html()))`.\n",
    "\n",
    "Above we saw how a dataclass behaves with the `__ft__` method defined. On a plain dataclass, `str()` will be called (but not escaped)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<main>Hero(title='<h1>Hello World</h1>', statement='This is a hero statement')</main>\n",
       "\n",
       "```"
      ],
      "text/plain": [
       "['main',\n",
       " (Hero(title='<h1>Hello World</h1>', statement='This is a hero statement'),),\n",
       " {}]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from dataclasses import dataclass\n",
    "\n",
    "@dataclass\n",
    "class Hero:\n",
    "    title: str\n",
    "    statement: str\n",
    "        \n",
    "# rendering the dataclass with the default method\n",
    "Main(\n",
    "    Hero(\"<h1>Hello World</h1>\", \"This is a hero statement\")\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<div>Let&#x27;s include some HTML here: &lt;div&gt;Some HTML&lt;/div&gt;</div>\n",
       "\n",
       "```"
      ],
      "text/plain": [
       "['div', (\"Let's include some HTML here: <div>Some HTML</div>\",), {}]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# This will display the HTML as text on your page\n",
    "Div(\"Let's include some HTML here: <div>Some HTML</div>\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```html\n",
       "<div><div><h1>Some HTML</h1></div></div>\n",
       "\n",
       "```"
      ],
      "text/plain": [
       "['div', ('<div><h1>Some HTML</h1></div>',), {}]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Keep the string untouched, will be rendered on the page\n",
    "Div(NotStr(\"<div><h1>Some HTML</h1></div>\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Custom exception handlers\n",
    "\n",
    "FastHTML allows customization of exception handlers, but does so gracefully. What this means is by default it includes all the `<html>` tags needed to display attractive content. Try it out!\n",
    "\n",
    "```python\n",
    "from fasthtml.common import *\n",
    "\n",
    "def not_found(req, exc): return Titled(\"404: I don't exist!\")\n",
    "\n",
    "exception_handlers = {404: not_found}\n",
    "\n",
    "app, rt = fast_app(exception_handlers=exception_handlers)\n",
    "\n",
    "@rt('/')\n",
    "def get():\n",
    "    return (Titled(\"Home page\", P(A(href=\"/oops\")(\"Click to generate 404 error\"))))\n",
    "\n",
    "serve()\n",
    "```\n",
    "\n",
    "We can also use lambda to make things more terse:\n",
    "\n",
    "```python\n",
    "from fasthtml.common import *\n",
    "\n",
    "exception_handlers={\n",
    "    404: lambda req, exc: Titled(\"404: I don't exist!\"),\n",
    "    418: lambda req, exc: Titled(\"418: I'm a teapot!\")\n",
    "}\n",
    "\n",
    "app, rt = fast_app(exception_handlers=exception_handlers)\n",
    "\n",
    "@rt('/')\n",
    "def get():\n",
    "    return (Titled(\"Home page\", P(A(href=\"/oops\")(\"Click to generate 404 error\"))))\n",
    "\n",
    "serve()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cookies\n",
    "\n",
    "We can set cookies using the `cookie()` function. In our example, we'll create a `timestamp` cookie."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import datetime\n",
    "from IPython.display import HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<!doctype html>\n",
       "\n",
       "<html>\n",
       "  <head>\n",
       "    <title>FastHTML page</title>\n",
       "  </head>\n",
       "  <body>\n",
       "Set to 2024-08-07 09:07:47.535449\n",
       "  </body>\n",
       "</html>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@rt(\"/settimestamp\")\n",
    "def get(req):\n",
    "    now = datetime.now()\n",
    "    return P(f'Set to {now}'), cookie('now', datetime.now())\n",
    "\n",
    "HTML(client.get('/settimestamp').text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's get it back using the same name for our parameter as the cookie name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Cookie was set at time 09:07:47.535456'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "@rt('/gettimestamp')\n",
    "def get(now:date): return f'Cookie was set at time {now.time()}'\n",
    "\n",
    "client.get('/gettimestamp').text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sessions\n",
    "\n",
    "For convenience and security, FastHTML has a mechanism for storing small amounts of data in the user's browser. We can do this by adding a `session` argument to routes. FastHTML sessions are Python dictionaries, and we can leverage to our benefit. The example below shows how to concisely set and get sessions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@rt('/adder/{num}')\n",
    "def get(session, num: int):\n",
    "    session.setdefault('sum', 0)\n",
    "    session['sum'] = session.get('sum') + num\n",
    "    return Response(f'The sum is {session[\"sum\"]}.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Toasts (also known as Messages)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Toasts, sometimes called \"Messages\" are small notifications usually in colored boxes used to notify users that something has happened. Toasts can be of four types:\n",
    "\n",
    "- info\n",
    "- success\n",
    "- warning\n",
    "- error\n",
    "\n",
    "Examples toasts might include:\n",
    "\n",
    "- \"Payment accepted\"\n",
    "- \"Data submitted\"\n",
    "- \"Request approved\"\n",
    "\n",
    " Toasts require the use of the `setup_toasts()` function plus every view needs these two features:\n",
    "\n",
    "- The session argument\n",
    "- Must return FT components\n",
    "\n",
    "```python\n",
    "setup_toasts(app) # <1>\n",
    "\n",
    "@rt('/toasting')\n",
    "def get(session):  # <2>\n",
    "    # Normally one toast is enough, this allows us to see\n",
    "    # different toast types in action.\n",
    "    add_toast(session, f\"Toast is being cooked\", \"info\")\n",
    "    add_toast(session, f\"Toast is ready\", \"success\")\n",
    "    add_toast(session, f\"Toast is getting a bit crispy\", \"warning\")\n",
    "    add_toast(session, f\"Toast is burning!\", \"error\")\n",
    "    return Titled(\"I like toast\") # <3>\n",
    "```\n",
    "\n",
    "1. `setup_toasts` is a helper function that adds toast dependencies. Usually this would be declared right after `fast_app()`\n",
    "2. Toasts require sessions\n",
    "3. Views with Toasts must return FT components."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Authentication and authorization"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In FastHTML the tasks of authentication and authorization are handled with Beforeware.  Beforeware are functions that run before the route handler is called. They are useful for global tasks like ensuring users are authenticated or have permissions to access a view.\n",
    "\n",
    "First, we write a function that accepts a request and session arguments:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Status code 303 is a redirect that can change POST to GET,\n",
    "# so it's appropriate for a login page.\n",
    "login_redir = RedirectResponse('/login', status_code=303)\n",
    "\n",
    "def user_auth_before(req, sess):\n",
    "    # The `auth` key in the request scope is automatically provided\n",
    "    # to any handler which requests it, and can not be injected\n",
    "    # by the user using query params, cookies, etc, so it should\n",
    "    # be secure to use.    \n",
    "    auth = req.scope['auth'] = sess.get('auth', None)\n",
    "    # If the session key is not there, it redirects to the login page.\n",
    "    if not auth: return login_redir"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we pass our `user_auth_before` function as the first argument into a `Beforeware` class. We also pass a list of regular expressions to the `skip` argument, designed to allow users to still get to the home and login pages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "beforeware = Beforeware(\n",
    "    user_auth_before,\n",
    "    skip=[r'/favicon\\.ico', r'/static/.*', r'.*\\.css', r'.*\\.js', '/login', '/']\n",
    ")\n",
    "\n",
    "app, rt = fast_app(before=beforeware)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unwritten quickstart sections\n",
    "\n",
    "- Forms\n",
    "- Websockets\n",
    "- Tables"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import nbdev; nbdev.nbdev_export()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
